import React from 'react'
import { Tag, Space } from 'antd'
import { useSelector, useDispatch } from 'react-redux'
import { closeTab, selectCurrentMenu } from '../../store/reducers/tab'
import { useLocation, useNavigate } from 'react-router-dom'

function CommonTag() {
  // 获取store的数据
  const tabsList = useSelector(state => state.tab.tabList)
  const currentMenu = useSelector(state => state.tab.currentMenu)

  //执行action
  const dispatch = useDispatch()

  // 获取路由路径
  const action = useLocation()

  // 路由跳转
  const navigate = useNavigate()

  //关闭tag
  const handleClose = (tag, index) => {

    let length = tabsList.length - 1
    dispatch(closeTab(tag))
    if (tag.path !== action.pathname) return
    // 关闭最后一个tag
    if (index === length) {
      const curData = tabsList[index - 1]
      dispatch(selectCurrentMenu(curData))
      navigate(curData.path)
    } else {
      if (tabsList.length > 1) {
        const nextData = tabsList[index + 1]
        dispatch(selectCurrentMenu(nextData))
        navigate(nextData.path)
      }
    }
  }
  // 点击tag
  const handleChange = tag => {

    dispatch(selectCurrentMenu(tag))
    navigate(tag.path)
  }

  // tag的显示
  const setTag = (flag, item, index) => {
    return flag ? (
      <Tag key={item.name} color="#55acee" closeIcon onClose={() => handleClose(item, index)}>
        {item.label}
      </Tag>
    ) : (
      <Tag key={item.name} onClick={() => handleChange(item)}>
        {item.label}
      </Tag>
    )
  }

  return (
    <>
      <Space size={[0, 8]} wrap className="pt-[0.3rem] pl-[0.3rem]">
        {currentMenu.name &&
          tabsList.map((item, index) => setTag(item.name == currentMenu.name, item, index))}
      </Space>
    </>
  )
}

export default CommonTag
